package cn.itcast.bos.realm;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.PermissionService;
import cn.itcast.bos.service.RoleService;
import cn.itcast.bos.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Think on 2017/10/7.
 */
public class BosRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;

    //实现登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("用户认证");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;
        //使用登录名查询数据库,返回用户的信息(登录名唯一)
        String username = usernamePasswordToken.getUsername();
        User user = userService.findByUsername(username);
        //登录名有误
        if(user==null){
            //返回值为null,表示登录名输入错误
            return null;
        }else{
            // 参数一： 期望登录后，将用户信息保存在Subject中的信息（相对于Session）
            // 参数二： 当返回用户密码时，securityManager安全管理器，自动比较返回密码和用户输入密码是否一致
            //       如果密码一致 登录成功， 如果密码不一致 报密码错误异常（IncorrectCredentialsException）
            // 参数三 ：realm名称
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }
    }

    //实现授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("用户授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //根据当前登录用户 查询该用户对应的角色和权限
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //调用业务层,查询角色
        List<Role> roleList = roleService.findAllRoles(user);
        for (Role role : roleList) {
            simpleAuthorizationInfo.addRole(role.getKeyword()); // roles[base]
        }
        //调用业务层,查询权限
        List<Permission> permissionList = permissionService.findAllPermission(user);
        for (Permission permission : permissionList) {
            simpleAuthorizationInfo.addStringPermission(permission.getKeyword());       // perms[courier:list]
        }
        return simpleAuthorizationInfo;
    }
}
